from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

import os, django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "stock_predict.settings")
django.setup()

from stock.models import Stock, StockDetail
import akshare as ak


# Create your views here.


def save_stock_data():
    if Stock.objects.count() == 0:
        print("正在获取股票数据")
        data = ak.stock_zh_a_spot_em()  # 获取东方财富网-沪深京 A 股-实时行情

        for i in range(len(data)):
            code = data["代码"][i]
            name = data["名称"][i]

            Stock.objects.create(code=code, name=name)

        print("股票数据获取成功")

    else:
        print("数据库已有股票数据")


save_stock_data()


def test(request):
    return JsonResponse({'code': 200, 'msg': 'success', 'data': {'message': 'Hello World!'}})


def stock(request):
    test_data = [
    ]
    return JsonResponse({'code': 200, 'msg': 'success', 'data': test_data})


def list_page(request):
    name = request.GET.get("name", None)
    page_num = int(request.headers.get("Pagenum", 1))
    page_size = int(request.headers.get("Pagesize", 10))
    if name:  # 如果查询输入不为空
        stock_query_by_code = Stock.objects.all().filter(code__contains=name)
        stock_query_by_name = Stock.objects.all().filter(name__contains=name)
    else:
        stock_query_by_code = Stock.objects.all()
        stock_query_by_name = Stock.objects.all()
    data = []
    for i in stock_query_by_name:
        data.append({"code": i.code, "name": i.name})
    for i in stock_query_by_code:
        data.append({"code": i.code, "name": i.name})
    pageRes = {
        "current": page_num,
        "pages": page_num,
        "size": page_size,
        "total": len(data),
        "records": data[page_size * (page_num - 1):page_size * page_num],
    }
    return JsonResponse({'code': 200, 'msg': 'success', 'data': pageRes})


def list_stock(request):
    data = {
    }
    return JsonResponse({'code': 200, 'msg': 'success', 'data': data})
